from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response

from Apps.Data.models import JobModel

from Utils.Constant import RESULT
# 职位搜索和筛选功能
# 允许用户根据地点、需要的技能、公司等标准来搜索和过滤可提供的职位。
from Apps.Data.serializer import JobModelSerializer


@api_view(['GET'])
def get_jobs(request):
    # 必传参数
    pageSize = request.GET.get('pageSize', None)
    pageNumber = request.GET.get('pageNumber', None)

    if pageSize is None or pageNumber is None:
        return Response({'status': RESULT['fail'], 'message': '参数不合法'})

    location = request.GET.get('location', None)
    skills = request.GET.get('skills', None)
    company = request.GET.get('company', None)

    # if location is None and skills is None and company is None:
    #     return Response({'status': RESULT['fail'], 'message': '参数不合法'})

    # 链式查找
    jobs = JobModel.objects
    if location:
        # 等值匹配
        jobs = jobs.filter(city_name=location)
    if skills:
        # Like匹配，对于多Tag查找使用拼接字符串实现
        jobs = jobs.filter(skills__contains=skills)
    if company:
        # Like匹配包含的
        jobs = jobs.filter(brand_name__contains=company)

    jobs = jobs.all()

    try:
        paginator = Paginator(jobs, pageSize)
        total_page = paginator.count
        total_index = int(total_page / int(pageSize) + 0.5)
    except EmptyPage as err:
        return Response({'status': RESULT['fail'], 'message': '没有找到相关记录'})

    return Response({
        'status': RESULT['success'],
        'total': f"总共：{total_index} 页",
        'count': f"总共：{total_page} 条记录",
        'data': JobModelSerializer(paginator.get_page(pageNumber), many=True).data
    })


